package com.bhs.sansonglogistics.ui.home;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.bhs.sansonglogistics.R;
import com.bhs.sansonglogistics.base.BaseBean;
import com.bhs.sansonglogistics.base.BaseFragment;
import com.bhs.sansonglogistics.bean.BusinessAdministrationBean;
import com.bhs.sansonglogistics.bean.CompanyApproveInfoBean;
import com.bhs.sansonglogistics.bean.OrderGoodsBean;
import com.bhs.sansonglogistics.bean.SourceGoodsDataBean;
import com.bhs.sansonglogistics.bean.UserInfoBean;
import com.bhs.sansonglogistics.bean.event.ApplicationStatus;
import com.bhs.sansonglogistics.bean.event.ListeningStatus;
import com.bhs.sansonglogistics.bean.event.NewMessage;
import com.bhs.sansonglogistics.bean.event.OrderEvent;
import com.bhs.sansonglogistics.bean.event.PreemptStatus;
import com.bhs.sansonglogistics.bean.event.RefreshEvent;
import com.bhs.sansonglogistics.dialog.BottomRefuseDialog;
import com.bhs.sansonglogistics.dialog.MyClickListener;
import com.bhs.sansonglogistics.dialog.MyClickListener2;
import com.bhs.sansonglogistics.dialog.PreemptDialog;
import com.bhs.sansonglogistics.dialog.QuotationReceivedSuccessfullyDialog;
import com.bhs.sansonglogistics.dialog.QuotedPriceDialog;
import com.bhs.sansonglogistics.net.NetApi;
import com.bhs.sansonglogistics.net.NetCallBack;
import com.bhs.sansonglogistics.net.RetrofitUtils;
import com.bhs.sansonglogistics.ui.adapter.SourceGoodsAdapter;
import com.bhs.sansonglogistics.ui.enterprise.AddLineActivity;
import com.bhs.sansonglogistics.ui.enterprise.EnterpriseCertificationActivity;
import com.bhs.sansonglogistics.ui.mine.OrderInformActivity;
import com.bhs.sansonglogistics.ui.order.HistoryOrderActivity;
import com.bhs.sansonglogistics.ui.order.OrderDetailsActivity;
import com.bhs.sansonglogistics.ui.order.SourceGoodsDetailsActivity;
import com.bhs.sansonglogistics.utils.LogUtils;
import com.bhs.sansonglogistics.utils.MyUtils;
import com.bhs.sansonglogistics.utils.SharedPreferencesUtils;
import com.bhs.sansonglogistics.utils.ToastUtil;
import com.bhs.sansonglogistics.utils.VoiceUtils;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.interfaces.OnConfirmListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.ResponseBody;
import retrofit2.Response;

public class SourceGoodsListFragment extends BaseFragment implements NetCallBack, View.OnClickListener {

    private int type;//1指派 2极速
    private RecyclerView rvList;

    private SourceGoodsAdapter sourceGoodsAdapter;
    private BasePopupView quotedPricePopupView;
    private final int ORDER_RECEIVING = 2;

    private SwipeRefreshLayout refreshLayout;
    private int page = 1;
    private Map<String, String> parameters = new HashMap<>();
    private TextView tvRedPacket;
    private LinearLayout ll_decertification, ll_go_to_check;
    private LinearLayout mLlLine;
    private String deliver_sn;
    private PreemptDialog dialog;//抢单
    private RelativeLayout mRlEmpty;
    private TextView mBtnHistory;
    private ImageView mIvAdvertising;
    private TextView tvDecertification;
    private boolean isPull;

    @Override
    public int initLayout() {
        return R.layout.fragment_source_goods_list;
    }

    public static SourceGoodsListFragment newInstance(int type) {
        SourceGoodsListFragment fragment = new SourceGoodsListFragment();
        Bundle args = new Bundle();
        args.putInt("type", type);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            type = getArguments().getInt("type");
        }
    }


    private void earlierInitView(View root) {
        rvList = root.findViewById(R.id.rv_list);
        tvRedPacket = root.findViewById(R.id.tv_redPacket);
        refreshLayout = root.findViewById(R.id.refreshLayout);
        ll_decertification = root.findViewById(R.id.ll_decertification);
        tvDecertification = root.findViewById(R.id.tv_decertification);
        tvDecertification.setOnClickListener(this);
        ll_go_to_check = root.findViewById(R.id.ll_go_to_check);
        root.findViewById(R.id.tv_GotoCheck).setOnClickListener(this);
        //下拉刷新和上拉加载
        //监听 刷新是回调
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 1;
                loadData();
            }
        });
        mLlLine = root.findViewById(R.id.ll_line);
        root.findViewById(R.id.tv_add).setOnClickListener(this);
        mRlEmpty = root.findViewById(R.id.rl_empty);
        mBtnHistory = root.findViewById(R.id.btn_history);
        mBtnHistory.setVisibility(View.VISIBLE);
        mBtnHistory.setOnClickListener(this);
        mIvAdvertising = root.findViewById(R.id.iv_advertising);
        Glide.with(getContext()).load(R.mipmap.ic_advertising).into(mIvAdvertising);
        isOpenVoice = SharedPreferencesUtils.getBoolean(getContext(), "voice", true);
        // listeningList = SharedPreferencesUtils.getBoolean(getContext(), "isOpenListening", true);
        listeningList = true;
    }

    private void earlierInitData() {
        dialog = new PreemptDialog(getActivity());
        dialog.setMyClickListener(new MyClickListener2() {
            @Override
            public void onClick(String id, String info) {
                page = 1;
                loadData();
                dialog.dismiss();
                if (id.equals("查看订单")) {
                    startActivity(new Intent(getActivity(), OrderDetailsActivity.class)
                            .putExtra("deliver_sn", deliver_sn));
                }
            }
        });
        sourceGoodsAdapter = new SourceGoodsAdapter(R.layout.item_source_goods, type);
        rvList.setAdapter(sourceGoodsAdapter);
        rvList.setLayoutManager(new LinearLayoutManager(getContext()));

        sourceGoodsAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (ll_decertification.getVisibility() == View.VISIBLE) {
                    ToastUtil.show("请先完成认证");
                    return;
                }
                OrderGoodsBean info = (OrderGoodsBean) adapter.getData().get(position);
                if (view.getId() == R.id.btn_preempt) {
                    //接单
                    preempt(info);

                } else if (view.getId() == R.id.btn_immediate_offer) {
                    //报价
                    QuotedPriceDialog quotedPriceDialog = new QuotedPriceDialog(SourceGoodsListFragment.this, null, info);

                    quotedPricePopupView = new XPopup.Builder(getContext())
                            .asCustom(quotedPriceDialog)
                            .show();
                    quotedPriceDialog.setMyClickListener(new MyClickListener() {
                        @Override
                        public void onClick(View v) {
                            page = 1;
                            loadData();
                            quotedPricePopupView.dismiss();
                        }
                    });
                } else if (view.getId() == R.id.btn_refuse) {
                    BottomRefuseDialog bottomRefuseDialog = new BottomRefuseDialog(SourceGoodsListFragment.this, null, info.getDeliver_sn());
                    new XPopup.Builder(getContext())
                            .asCustom(bottomRefuseDialog)
                            .show();
                    bottomRefuseDialog.setMyClickListener(new MyClickListener() {
                        @Override
                        public void onClick(View v) {
                            page = 1;
                            loadData();
                        }
                    });
                }
            }
        });
        sourceGoodsAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (ll_decertification.getVisibility() == View.VISIBLE) {
                    ToastUtil.show("请先完成认证");
                    return;
                }
                OrderGoodsBean info = (OrderGoodsBean) adapter.getData().get(position);
                startActivity(new Intent(getActivity(), SourceGoodsDetailsActivity.class)
                        .putExtra("deliver_sn", info.getDeliver_sn())
                        .putExtra("type", type)
                        .putExtra("subscribe", info.getIs_yuyue() > 0)
                        .putExtra("quoted_price", info.getQuoted_price())
                        .putExtra("quoted_create_time", info.getQuoted_create_time()));

            }
        });


        loadData();
    }

    Handler handler = new Handler();
    private Runnable heartBeatRunnable = new Runnable() {
        @Override
        public void run() {
            if (dialog.isWinningOrder) {
                dialog.overtime();
            }

        }
    };

    private void preempt(OrderGoodsBean info) {
        new XPopup.Builder(getContext())
                .isDestroyOnDismiss(false)
                .asConfirm("提示", "您确定接单吗？",
                        "取消", "确定",
                        new OnConfirmListener() {
                            @Override
                            public void onConfirm() {
                                deliver_sn = info.getDeliver_sn();
                                if (type == 2) {
                                    networkRequest(netApi.preempt(deliver_sn), SourceGoodsListFragment.this, 777);
                                    dialog.show();
                                    dialog.winningOrder();
                                    dialog.deliver_sn = info.getDeliver_sn();
                                    //抢单时间过长 直接显示失败
                                    handler.postDelayed(heartBeatRunnable, 1000 * 32);
                                } else {
                                    networkRequest(netApi.orderReceiving(info.getDeliver_sn()), SourceGoodsListFragment.this, ORDER_RECEIVING);
                                }
                            }
                        }, null, false)
                .show();
    }

    @Override
    public void prestrain() {
        super.prestrain();
        //注册监听
        EventBus.getDefault().register(this);
        earlierInitView(view);
        earlierInitData();
    }


    @Override
    public void initView(View root) {

    }

    @Override
    public void onResumes() {
        super.onResumes();
        if (!Settings.canDrawOverlays(getActivity())) {
            ll_go_to_check.setVisibility(View.VISIBLE);
        } else {
            ll_go_to_check.setVisibility(View.GONE);
        }
    }

    private void loadData() {
        if (netApi == null) {
            //创建网络请求接口对象实例
            netApi = RetrofitUtils.getInstance().getRetrofit().create(NetApi.class);
        }
        //是否开启听单
        if (listeningList || type == 1) {
            parameters.put("page", String.valueOf(page));
            parameters.put("limit", "20");
            parameters.put("search_type", String.valueOf(type));
            networkRequest(netApi.getOrderList(parameters), this);
        } else {
            ToastUtil.show("未开启听单");
            refreshLayout.setRefreshing(false);
        }


        if (!SharedPreferencesUtils.getBoolean(getContext(), "isSpecialLine", false)) {
            networkRequest(netApi.getIndexInfo(), this, 888);
        } else {
            mLlLine.setVisibility(View.GONE);
        }
        if (!SharedPreferencesUtils.getBoolean(getContext(), "SuccessfulAuthentication", false)) {
            networkRequest(netApi.getCompanyApproveInfo(), this, 999);
        } else {
            ll_decertification.setVisibility(View.GONE);
        }
    }


    @Override
    public void initData() {
        //提前加载我的页面数据
        networkRequest(netApi.get_user_info(), this, 555);
    }


    @Override
    public void onResponse(int requestCode, String json, Response<ResponseBody> response) throws Exception {
        if (requestCode == ORDER_RECEIVING) {
            //接单
            BaseBean dataBean = new Gson().fromJson(json, BaseBean.class);
            if (dataBean.isStatus()) {
                VoiceUtils.orderReceiving(getContext());
                QuotationReceivedSuccessfullyDialog confirmDialog = new QuotationReceivedSuccessfullyDialog(getContext(), 1);
                new XPopup.Builder(getContext())
                        .asCustom(confirmDialog)
                        .show();
                confirmDialog.setMyClickListener(new MyClickListener() {
                    @Override
                    public void onClick(View v) {
                        confirmDialog.dismiss();
                        page = 1;
                        loadData();
                        if (v.getId() == R.id.btn_check_order) {
                            startActivity(new Intent(getActivity(), OrderDetailsActivity.class)
                                    .putExtra("deliver_sn", deliver_sn));
                        }

                    }
                });
            } else {
                ToastUtil.show(dataBean.getMsg());
            }
        } else if (requestCode == 999) {
            try {
                //判断是否已经认证
                CompanyApproveInfoBean companyApproveInfoBean = new Gson().fromJson(json, CompanyApproveInfoBean.class);
                if (companyApproveInfoBean.isStatus()) {
                    SharedPreferencesUtils.saveBoolean(getContext(), "SuccessfulAuthentication", companyApproveInfoBean.getData().getCompany_approve_info().getStatus() == 1);
                    if (companyApproveInfoBean.getData().getCompany_approve_info().getStatus() != 1) {
                        if (companyApproveInfoBean.getData().getCompany_approve_info().getStatus() == 0) {
                            tvDecertification.setText("认证中");
                        } else if (companyApproveInfoBean.getData().getCompany_approve_info().getStatus() == 2) {
                            tvDecertification.setText("认证失败");
                        }
                        ll_decertification.setVisibility(View.VISIBLE);
                    } else {
                        ll_decertification.setVisibility(View.GONE);
                    }
                }
            } catch (Exception e) {
                //这个如果没有认证数据返回的数组 所以会捕获异常
                ll_decertification.setVisibility(View.VISIBLE);
            }

        } else if (requestCode == 888) {
            //判断是否有专线
            BusinessAdministrationBean bean = new Gson().fromJson(json, BusinessAdministrationBean.class);
            if (bean.isStatus()) {
                if (bean.getData().getLine_num().equals("0")) {
                    mLlLine.setVisibility(View.VISIBLE);
                } else {
                    mLlLine.setVisibility(View.GONE);
                    SharedPreferencesUtils.saveBoolean(getContext(), "isSpecialLine", true);
                }
            }
        } else if (requestCode == 777) {
            BaseBean bean = new Gson().fromJson(json, BaseBean.class);
            if (!bean.isStatus()) {
                handler.removeCallbacks(heartBeatRunnable);
                dialog.error(bean.getMsg());
            }

        } else if (requestCode == 555) {
            UserInfoBean infoBean = new Gson().fromJson(json, UserInfoBean.class);
            EventBus.getDefault().postSticky(infoBean);
        } else {
            refreshLayout.setRefreshing(false);
            SourceGoodsDataBean dataBean = new Gson().fromJson(json, SourceGoodsDataBean.class);
            if (dataBean.isStatus()) {
                if (page == 1) {
                    if (!MyUtils.isEmpty(dataBean.getData().getList())) {
                        mRlEmpty.setVisibility(View.GONE);
                        rvList.setVisibility(View.VISIBLE);
                    } else {
                        mRlEmpty.setVisibility(View.VISIBLE);
                        rvList.setVisibility(View.GONE);
                    }
                    sourceGoodsAdapter.setNewData(dataBean.getData().getList());
                    EventBus.getDefault().post(new OrderEvent(sourceGoodsAdapter.getData().size()));
                    //当通过
                    if (!isPull) {
                        isPull = true;
                        sourceGoodsAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
                            @Override
                            public void onLoadMoreRequested() {
                                page++;
                                loadData();
                            }
                        }, rvList);
                    }
                } else {
                    sourceGoodsAdapter.loadMoreComplete();
                    sourceGoodsAdapter.addData(dataBean.getData().getList());
                }
                if (sourceGoodsAdapter.getData().size() >= dataBean.getData().getTotal_count()) {
                    sourceGoodsAdapter.loadMoreEnd();
                }

            } else {
                ToastUtil.show(dataBean.getMsg());
            }
        }
    }

    @Override
    public void onFailure(int requestCode) {
        if (requestCode == 0) {
            refreshLayout.setRefreshing(false);
            sourceGoodsAdapter.loadMoreComplete();
        }
    }

    @Subscribe
    public void onEvent(RefreshEvent event) {
        if (event.getType() == type) {
            page = 1;
            loadData();
        }
    }


    private boolean listeningList;//是否听单
    private boolean isOpenVoice;//是否开启声音

    @SuppressLint("NotifyDataSetChanged")
    @Subscribe
    public void onEvent(ListeningStatus event) {
        listeningList = event.isListeningList();
        isOpenVoice = event.isOpenVoice();
        if (!listeningList) {
            sourceGoodsAdapter.getData().clear();
            sourceGoodsAdapter.notifyDataSetChanged();
            mRlEmpty.setVisibility(View.VISIBLE);
        } else {
            page = 1;
            loadData();
        }
    }

    @Subscribe
    public void onEvent(OrderGoodsBean event) {
        if (event.getOrder_type() == type) {
            rvList.setVisibility(View.VISIBLE);
            sourceGoodsAdapter.addData(0, event);
            mRlEmpty.setVisibility(View.GONE);
            rvList.scrollToPosition(0);
            if (isOpenVoice) {
                VoiceUtils.newOrder(getContext());
            }
        }
    }

    private boolean isOnPause;//是否在当前页

    //抢单状态 event.getDeliver_type() == 3议价单没有弹窗
    @Subscribe
    public void onEvent(PreemptStatus event) {
        if (event.getOrder_type() == type) {
            if ((dialog != null && event.getDeliver_sn().equals(dialog.deliver_sn)) || event.getDeliver_type() == 3) {
                handler.removeCallbacks(heartBeatRunnable);
                if (event.isPreemptStatus()) {
                    deliver_sn = event.getDeliver_sn();
                    dialog.succeed(event.getDeliver_type());
                } else {
                    dialog.failure();
                }
            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        isOnPause = true;
    }

    @Override
    public void onResume() {
        super.onResume();
        isOnPause = false;
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.tv_decertification) {
            startActivity(new Intent(getActivity(), EnterpriseCertificationActivity.class));
        } else if (view.getId() == R.id.tv_add) {
            startActivity(new Intent(getActivity(), AddLineActivity.class));
        } else if (view.getId() == R.id.tv_GotoCheck) {
            startActivity(new Intent(getActivity(), OrderInformActivity.class));
        } else if (view.getId() == R.id.btn_history) {
            startActivity(new Intent(getActivity(), HistoryOrderActivity.class));
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}